package ru.mcfr.oxygen.updater.web;

import org.apache.log4j.Logger;
import sun.misc.BASE64Encoder;
import sun.net.www.protocol.http.HttpURLConnection;

import java.io.IOException;
import java.io.InputStream;
import java.net.InetSocketAddress;
import java.net.Proxy;
import java.net.URL;
import java.util.Properties;

/**
 * Created by IntelliJ IDEA.
 * User: ws
 * Date: 27.04.11
 * Time: 18:56
 * To change this template use File | Settings | File Templates.
 * @use-proxy
 * @proxy-server
 * @proxy-port
 * @proxy-user-name
 * @proxy-user-password
 */
public abstract class AbstractConnector {

    protected Logger logger = Logger.getLogger(AbstractConnector.class);

    protected Properties props;

    public AbstractConnector(Properties p){
        this.props = new Properties(p);
    }

    public abstract InputStream get(String url);

    private HttpURLConnection simpleConnectToUrl(String sUrl){
        sUrl = sUrl + "?username=" + System.getProperty("user.name") + "&osname=" + System.getProperty("os.name");
        HttpURLConnection urlConn = null;
        try{
			URL url = new URL(sUrl);
			if (props.getProperty("use-proxy").equals("true")){
                if (props.getProperty("proxy-server").isEmpty())
                    throw new IllegalStateException("Settings is not loaded");
				Proxy proxy = new Proxy(Proxy.Type.HTTP, new InetSocketAddress(props.getProperty("proxy-server"),
                                                                                Integer.valueOf(props.getProperty("proxy-port", "8080"))));
				urlConn = new HttpURLConnection(url, proxy);
				BASE64Encoder encoder = new BASE64Encoder();
				String passPhrase = props.getProperty("proxy-user-name") + ":" + props.getProperty("proxy-user-password");
				String encodedUserPwd = encoder.encode(passPhrase.getBytes());
				urlConn.setRequestProperty("Proxy-Authorization", "Basic " + encodedUserPwd);
			}
			else
				urlConn = new HttpURLConnection(url, null);
        }catch (IOException e) {
			logger.error(e.getLocalizedMessage());
		}
        return urlConn;
    }

    public HttpURLConnection connectToURL(String sUrl){
		try{
			HttpURLConnection urlConn = simpleConnectToUrl(sUrl);

			urlConn.setRequestMethod("GET");
			urlConn.setDoInput (true);
			urlConn.setDoOutput (true);
			urlConn.setUseCaches (false);

			urlConn.connect();

			if (urlConn.getResponseCode() < HttpURLConnection.HTTP_MULT_CHOICE)//300
				return urlConn;
			else
				return urlConn;
		}catch (IOException e) {
			logger.error(e.getLocalizedMessage());
		}
		return null;
	}

}
